package Sort2018;

/**
 * Created by 雷文康 on 2018/2/26.
 */
public class MergeSort {

    public static void main(String[] args) {
        int[] array = {3,8,4,6,7,2,5,9,1};
        mergeSort(array);
        for (int i = 0; i < array.length; i++){
            System.out.print(array[i]);
        }
    }

    public static void mergeSort(int[] array) {
        if (array == null || array.length == 0) {
            return;
        }
        mergeSort(array, 0, array.length - 1);
    }
    public static void mergeSort(int[] array, int start, int end){
        if (start >= end) {
            return;
        }
        int mid = (start + end) / 2;
        mergeSort(array, start, mid);
        mergeSort(array,mid + 1, end);
        merge(array, start, mid, end);
    }

    public static void merge(int[] array, int start, int mid, int end) {
        int first = start;
        int second = mid + 1;
        int third = 0;
        int[] thirdArr = new int[end - start + 1];
        while (first <= mid && second <= end) {
            if (array[first] <= array[second]) {
                thirdArr[third++] = array[first++];
            } else {
                thirdArr[third++] = array[second++];
            }
        }
        while (first <= mid){
            thirdArr[third++] = array[first++];
        }
        while (second <= end){
            thirdArr[third++] = array[second++];
        }
        int i = 0;
        while (start <= end) {
            array[start++] = thirdArr[i++];
        }
    }
}
